package GUI.Ventas;

import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;

import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import client.entities.ClientVO;
import GUI.Administracion.Exceptions.ExcepcionesMenuVentas;
import article.entities.ArticleVO;
import article.exceptions.OutOfStockIngredientsException;
import sale.entities.OrderVO;
import sale.exceptions.EmptyOrderException;
import sale.exceptions.EmptySaleExcpetion;
import service.ServiceFacade;
import service.article.exceptions.ProxyException;
import service.sale.interfaces.SaleProxyMgt;

public class NuevaVentaDelivery extends Dialog {

	protected Object result;
	protected Shell shell;
	private Table table;
	private Text direccion;
	private Text Telefono;
	ArrayList<ArticleVO> articulos;
	ArrayList<String > espec;
	Display display;
	OrderVO orden;
	ClientVO cl;
	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public NuevaVentaDelivery( Shell parent, int style, ArrayList<ArticleVO> arts, ArrayList<String> esp, OrderVO o,ClientVO c) {
		super(parent, style);
		
		orden=o;
		articulos = arts;
		espec=esp;
		cl=c;
		setText("SWT Dialog");
	}

	/**
	 * Open the dialog.
	 * @return the result
	 */
	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), getStyle());
		shell.setSize(651, 399);
		shell.setText(getText());
		shell.setLayout(new FormLayout());
		
	
		/*Shell [] shells = display.getShells();
		for(int i=0;i<shells.length;i++){
			if (shells[i]!=shell){
				shells[i].dispose();
			}
		}
		*/
		Label lblDireccion = new Label(shell, SWT.NONE);
		FormData fd_lblDireccion = new FormData();
		fd_lblDireccion.top = new FormAttachment(0, 53);
		fd_lblDireccion.left = new FormAttachment(0, 10);
		lblDireccion.setLayoutData(fd_lblDireccion);
		lblDireccion.setText("Direccion");
		
		Label lblTelefono = new Label(shell, SWT.NONE);
		FormData fd_lblTelefono = new FormData();
		fd_lblTelefono.top = new FormAttachment(lblDireccion, 29);
		fd_lblTelefono.left = new FormAttachment(lblDireccion, 0, SWT.LEFT);
		lblTelefono.setLayoutData(fd_lblTelefono);
		lblTelefono.setText("Telefono");
		
		Label lblArticulos = new Label(shell, SWT.NONE);
		FormData fd_lblArticulos = new FormData();
		fd_lblArticulos.top = new FormAttachment(lblTelefono, 31);
		fd_lblArticulos.left = new FormAttachment(lblDireccion, 0, SWT.LEFT);
		lblArticulos.setLayoutData(fd_lblArticulos);
		lblArticulos.setText("Articulos");
		
		table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
		FormData fd_table = new FormData();
		fd_table.bottom = new FormAttachment(lblArticulos, 157, SWT.BOTTOM);
		fd_table.top = new FormAttachment(lblArticulos, 6);
		fd_table.left = new FormAttachment(0, 10);
		fd_table.right = new FormAttachment(0, 387);
		table.setLayoutData(fd_table);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		TableColumn tblclmnArticulo = new TableColumn(table, SWT.NONE);
		tblclmnArticulo.setWidth(100);
		tblclmnArticulo.setText("Articulo");
		
		TableColumn tblclmnPrecio = new TableColumn(table, SWT.NONE);
		tblclmnPrecio.setWidth(100);
		tblclmnPrecio.setText("Precio");
		
		TableColumn tblclmnEspecificaciones = new TableColumn(table, SWT.NONE);
		tblclmnEspecificaciones.setWidth(280);
		tblclmnEspecificaciones.setText("Especificaciones");
		
		Label lblCliente = new Label(shell, SWT.NONE);
		FormData fd_lblCliente = new FormData();
		fd_lblCliente.top = new FormAttachment(lblDireccion, 0, SWT.TOP);
		lblCliente.setLayoutData(fd_lblCliente);
		lblCliente.setText("Cliente");
		
		Button btnAgregarArticulo = new Button(shell, SWT.NONE);
		btnAgregarArticulo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				
				if(orden==null){
					ArrayList<ArticleVO> a = new ArrayList<ArticleVO>();
					ArrayList<String> es = new ArrayList <String>();
					OrderVO o = new OrderVO (a,es);
					orden=o;
					orden.setAddress(direccion.getText());
					orden.setTel(Telefono.getText());
					AgregarArticulosDelivery ag = new AgregarArticulosDelivery(shell, shell.getStyle(),null, -2, 0, orden);
				
				
			//Shell parent, int style, SaleVO sale, int m, int op, OrderVO o
		
				try {
					
					shell.setVisible(false);
					ag.open();
				} catch (RemoteException e1) {
					ExcepcionesMenuVentas ventana = new ExcepcionesMenuVentas (shell, shell.getStyle(), "Error de Conexion con el Servidor");
					ventana.open();
					shell.dispose();
					e1.printStackTrace();
				} catch (ProxyException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}}
				
				else{
					AgregarArticulosDelivery ag = new AgregarArticulosDelivery(shell, shell.getStyle(),null, -2, 0, orden);
					
					
					//Shell parent, int style, SaleVO sale, int m, int op, OrderVO o
				
						try {
							
							shell.setVisible(false);
							ag.open();
						} catch (RemoteException e1) {
							ExcepcionesMenuVentas ventana = new ExcepcionesMenuVentas (shell, shell.getStyle(), "Error de Conexion con el Servidor");
							ventana.open();
							shell.dispose();
							e1.printStackTrace();
						} catch (ProxyException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					
				}
			}
		});
		
		FormData fd_btnAgregarArticulo = new FormData();
		fd_btnAgregarArticulo.top = new FormAttachment(table, 0, SWT.TOP);
		fd_btnAgregarArticulo.left = new FormAttachment(table, 6);
		btnAgregarArticulo.setLayoutData(fd_btnAgregarArticulo);
		btnAgregarArticulo.setText("Agregar Articulo");
		
		direccion = new Text(shell, SWT.BORDER);
		fd_lblCliente.left = new FormAttachment(direccion, 73);
		FormData fd_direccion = new FormData();
		fd_direccion.right = new FormAttachment(lblDireccion, 204, SWT.RIGHT);
		fd_direccion.top = new FormAttachment(0, 48);
		fd_direccion.left = new FormAttachment(lblDireccion, 24);
		direccion.setLayoutData(fd_direccion);
		
		Telefono = new Text(shell, SWT.BORDER);
		FormData fd_Telefono = new FormData();
		fd_Telefono.right = new FormAttachment(direccion, -94, SWT.RIGHT);
		fd_Telefono.top = new FormAttachment(direccion, 24);
		fd_Telefono.left = new FormAttachment(lblTelefono, 28);
		Telefono.setLayoutData(fd_Telefono);
		
		Button btnNewButton = new Button(shell, SWT.NONE);
		
			btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(orden ==null){
					
				}
				else{
					SaleProxyMgt uso = ServiceFacade.getInstance().getSaleProxyMgt();
					try {
						if(cl==null){
						uso.newDelSale(orden, orden.getAddress(), orden.getTel(),-1);
						shell.close();}
						else{
							uso.newDelSale(orden, orden.getAddress(), orden.getTel(),cl.getClientId());
							shell.close();}
						}
					 catch (RemoteException e1) {
						 ExcepcionesMenuVentas ventana = new ExcepcionesMenuVentas (shell, shell.getStyle(), "Error de Conexion con el Servidor");
							ventana.open();
							shell.dispose();
						e1.printStackTrace();
					} catch (ProxyException e1) {
						
						e1.printStackTrace();
					} catch (EmptyOrderException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (OutOfStockIngredientsException e1) {
					ArrayList<ArticleVO> g =	e1.getArts();
					String m = "No se puede realizar el pedido. Ingredientes faltantes: ";
					for(int i = 0; i<g.size();i++){
						m = m + " " + g.get(i).getName();
					}
						ExcepcionesMenuVentas ventana = new ExcepcionesMenuVentas (shell, shell.getStyle(), m);
						ventana.open();
						shell.dispose();
						e1.printStackTrace();
					}
				}
			}
		}); 
		
		FormData fd_btnNewButton = new FormData();
		fd_btnNewButton.top = new FormAttachment(table, 16);
		fd_btnNewButton.left = new FormAttachment(direccion, 0, SWT.LEFT);
		btnNewButton.setLayoutData(fd_btnNewButton);
		btnNewButton.setText("Aceptar y Enviar orden a la Cocina");
		
		Label lblTotalAPagar = new Label(shell, SWT.NONE);
		FormData fd_lblTotalAPagar = new FormData();
		fd_lblTotalAPagar.top = new FormAttachment(btnAgregarArticulo, 70);
		fd_lblTotalAPagar.left = new FormAttachment(table, 6);
		lblTotalAPagar.setLayoutData(fd_lblTotalAPagar);
		lblTotalAPagar.setText("Total a Pagar");
		
		Label total = new Label(shell, SWT.NONE);
		FormData fd_total = new FormData();
		fd_total.bottom = new FormAttachment(lblTotalAPagar, 0, SWT.BOTTOM);
		fd_total.right = new FormAttachment(100);
		total.setLayoutData(fd_total);
		if (this.articulos != null && this.articulos.size() > 0) {
			BigDecimal aux = new BigDecimal(0);
			for (ArticleVO o : this.articulos)
				aux = aux.add(new BigDecimal(o.getPrice()));
			total.setText(aux.toString());
		} else
			total.setText("0");
		
		Label label = new Label(shell, SWT.NONE);
		FormData fd_label = new FormData();
		fd_label.right = new FormAttachment(100, -227);
		fd_label.bottom = new FormAttachment(lblTelefono, 0, SWT.BOTTOM);
		label.setLayoutData(fd_label);
		
		Label cliente = new Label(shell, SWT.NONE);
		FormData fd_cliente = new FormData();
		fd_cliente.right = new FormAttachment(btnAgregarArticulo, 0, SWT.RIGHT);
		fd_cliente.bottom = new FormAttachment(label, -29);
		fd_cliente.left = new FormAttachment(label, 0, SWT.LEFT);
		cliente.setLayoutData(fd_cliente);
		cliente.setText("New Label");
		
		Button btnNewButton_1 = new Button(shell, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(orden == null){
					ArrayList<ArticleVO> a = new ArrayList<ArticleVO>();
					ArrayList<String> es = new ArrayList <String>();
					OrderVO o = new OrderVO (a,es);
					orden=o;
					orden.setAddress(direccion.getText());
					orden.setTel(Telefono.getText());
					//Shell parent, int style, OrderVO o, SaleVO s, int opcion
					selectClient select = new selectClient (shell, shell.getStyle(), orden, null, 3
							);
					shell.setVisible(false);
					select.open();
					
				}
				else{
				selectClient select = new selectClient (shell, shell.getStyle(), orden, null, 3);
				shell.setVisible(false);
				select.open();
			}}
		});
		FormData fd_btnNewButton_1 = new FormData();
		fd_btnNewButton_1.top = new FormAttachment(lblDireccion, -7, SWT.TOP);
		fd_btnNewButton_1.right = new FormAttachment(100, -10);
		btnNewButton_1.setLayoutData(fd_btnNewButton_1);
		btnNewButton_1.setText("Buscar");

	
	
	if(orden != null){
		for (int i=0;i<orden.getArts().size();i++){
			TableItem tableItem = new TableItem(table, SWT.NONE);
			tableItem.setText(0,orden.getArts().get(i).getName());
			tableItem.setText(1, String.valueOf(orden.getArts().get(i).getPrice()));
			tableItem.setText(2, orden.getEspecif().get(i));
		}
		Telefono.setText(orden.getTel());
		direccion.setText(orden.getAddress());
		if(cl!=null){
			cliente.setText(String.valueOf(cl.getClientId()));
		}
		else{
			cliente.setText("Seleccione Cliente si Aplica");
		}
		
	}
	else{
		cliente.setText("Seleccione Cliente si Aplica");
	}

}
}
